<template>
  <div class="requirement-management">
    <div class="requirement-header">
      <div class="header-left">
        <el-button type="primary" icon="el-icon-plus" @click="showAddRequirementDialog">添加需求</el-button>
        <span class="header-desc">需求是项目推进的核心，支持按模块、状态、优先级筛选和搜索。</span>
      </div>
      <div class="header-right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索需求（标题/描述）"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
        ></el-input>
        <el-select v-model="filterStatus" placeholder="状态筛选" clearable class="filter-select">
          <el-option
            v-for="status in statusOptions"
            :key="status.value"
            :label="status.label"
            :value="status.value">
          </el-option>
        </el-select>
      </div>
    </div>

    <el-table 
      :data="filteredRequirements" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
      highlight-current-row
      :empty-text="emptyText">
      <el-table-column prop="title" label="需求标题" min-width="200">
        <template slot-scope="scope">
          <div class="requirement-title">
            <i class="el-icon-document"></i>
            <span class="title-text">{{ scope.row.title }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="module" label="所属模块" width="150">
        <template slot-scope="scope">
          <el-tag size="medium" effect="plain">{{ scope.row.module }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="100">
        <template slot-scope="scope">
          <el-tag :type="getPriorityType(scope.row.priority)" effect="dark">
            {{ scope.row.priority }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" effect="dark">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deadline" label="截止日期" width="120">
        <template slot-scope="scope">
          <span :class="{ 'deadline-warning': isDeadlineWarning(scope.row.deadline) }">
            {{ formatDate(scope.row.deadline) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button-group>
            <el-button 
              size="mini" 
              type="primary" 
              icon="el-icon-edit"
              @click="editRequirement(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="danger" 
              icon="el-icon-delete"
              @click="deleteRequirement(scope.row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑需求对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @closed="resetForm">
      <el-form 
        :model="requirementForm" 
        :rules="rules" 
        ref="requirementForm" 
        label-width="100px"
        class="requirement-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="需求标题" prop="title">
              <el-input v-model="requirementForm.title" placeholder="请输入需求标题"></el-input>
            </el-form-item>
            <el-form-item label="所属模块" prop="module">
              <el-select v-model="requirementForm.module" placeholder="请选择模块" style="width: 100%">
                <el-option
                  v-for="module in modules"
                  :key="module.name"
                  :label="module.name"
                  :value="module.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="requirementForm.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="高" value="高"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="低" value="低"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="requirementForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待处理" value="待处理"></el-option>
                <el-option label="进行中" value="进行中"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已拒绝" value="已拒绝"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="截止日期" prop="deadline">
              <el-date-picker
                v-model="requirementForm.deadline"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="需求描述" prop="description">
              <el-input 
                type="textarea" 
                v-model="requirementForm.description" 
                :rows="4"
                placeholder="请输入需求描述">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRequirement" :loading="submitting">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { requirementService, moduleService } from '@/services/projectService'

export default {
  name: 'RequirementManagement',
  data() {
    return {
      loading: false,
      submitting: false,
      requirements: [],
      modules: [],
      searchQuery: '',
      filterStatus: '',
      dialogVisible: false,
      dialogTitle: '添加需求',
      requirementForm: {
        title: '',
        module: '',
        priority: '中',
        status: '待处理',
        deadline: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入需求标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        module: [
          { required: true, message: '请选择所属模块', trigger: 'change' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        deadline: [
          { required: true, message: '请选择截止日期', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入需求描述', trigger: 'blur' }
        ]
      },
      statusOptions: [
        { label: '待处理', value: '待处理' },
        { label: '进行中', value: '进行中' },
        { label: '已完成', value: '已完成' },
        { label: '已拒绝', value: '已拒绝' }
      ],
      emptyText: '暂无数据'
    }
  },
  computed: {
    filteredRequirements() {
      let result = this.requirements

      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(req => 
          req.title.toLowerCase().includes(query) ||
          req.description.toLowerCase().includes(query)
        )
      }

      if (this.filterStatus) {
        result = result.filter(req => req.status === this.filterStatus)
      }

      return result
    }
  },
  methods: {
    showAddRequirementDialog() {
      this.dialogTitle = '添加需求'
      this.loadModules()
      this.dialogVisible = true
    },
    editRequirement(row) {
      this.dialogTitle = '编辑需求'
      this.loadModules()
      this.requirementForm = { ...row }
      this.dialogVisible = true
    },
    deleteRequirement(row) {
      this.$confirm('确认删除该需求吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        requirementService.deleteRequirement(row.id)
        this.loadRequirements()
        this.$message.success('删除成功')
        this.$root.$emit('requirements-updated')
      }).catch(() => {})
    },
    submitRequirement() {
      this.$refs.requirementForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          try {
            requirementService.saveRequirement(this.requirementForm)
            this.dialogVisible = false
            this.loadRequirements()
            this.$message.success('保存成功')
            this.$root.$emit('requirements-updated')
          } catch (error) {
            this.$message.error('保存失败：' + error.message)
          } finally {
            this.submitting = false
          }
        }
      })
    },
    resetForm() {
      if (this.$refs.requirementForm) {
        this.$refs.requirementForm.resetFields()
      }
      this.requirementForm = {
        title: '',
        module: '',
        priority: '中',
        status: '待处理',
        deadline: '',
        description: ''
      }
    },
    getPriorityType(priority) {
      const priorityMap = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      }
      return priorityMap[priority] || 'info'
    },
    getStatusType(status) {
      const statusMap = {
        '待处理': 'info',
        '进行中': 'warning',
        '已完成': 'success',
        '已拒绝': 'danger'
      }
      return statusMap[status] || 'info'
    },
    formatDate(date) {
      if (!date) return ''
      return date
    },
    isDeadlineWarning(date) {
      if (!date) return false
      const deadline = new Date(date)
      const today = new Date()
      const diffDays = Math.ceil((deadline - today) / (1000 * 60 * 60 * 24))
      return diffDays <= 3 && diffDays >= 0
    },
    loadRequirements() {
      this.loading = true
      try {
        this.requirements = requirementService.getRequirements()
      } catch (error) {
        this.$message.error('加载需求列表失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    loadModules() {
      try {
        const modules = moduleService.getModules()
        if (modules.length === 0) {
          this.$message.warning('请先添加模块')
        }
        this.modules = modules
      } catch (error) {
        this.$message.error('加载模块列表失败：' + error.message)
      }
    }
  },
  created() {
    this.loadRequirements()
    this.loadModules()
    this.$root.$on('modules-updated', this.loadModules)
  },
  beforeDestroy() {
    this.$root.$off('modules-updated', this.loadModules)
  },
  watch: {
    // '$store.state.modules': {
    //   handler() {
    //     this.loadModules()
    //   },
    //   deep: true
    // }
  }
}
</script>

<style scoped>
.requirement-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.requirement-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-desc {
  color: #909399;
  font-size: 15px;
  margin-left: 12px;
}

.header-right {
  display: flex;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.requirement-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.requirement-title i {
  color: #409EFF;
}

.title-text {
  font-weight: 500;
  font-size: 16px;
}

.requirement-form {
  padding: 20px 10px 0 10px;
}

.deadline-warning {
  color: #E6A23C;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-table__empty-block) {
  min-height: 120px;
}
</style> 